package com.liumin.comlink.http.request;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 文件上传
 * 2020/1/4 9:57
 *
 * @author LiuWeiHao
 * Email 872235631@qq.com
 */
public class UploadUtil {
    /**
     * 多文件上传
     *
     * @param files 文件集合
     * @return List<MultipartBody.Part>
     */
    public static List<MultipartBody.Part> filesToMultipartBodyParts(List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        for (int i = 0, size = files.size(); i < size; i++) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), files.get(i));
            MultipartBody.Part part = MultipartBody.Part.createFormData("file" + i, files.get(i).getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }

    /**
     * 单文件上传
     *
     * @param file 文件
     * @return MultipartBody.Part
     */
    public static MultipartBody.Part fileToMultipartBodyPart(File file) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
        return MultipartBody.Part.createFormData("picture", file.getName(), requestBody);
    }
}
